import importlib
import json

from zkl_pyutils_fsspec import Fs

from .metadata import DatasetMetadata

dataset_metadata_file_name = "dataset.json"


def load_dataset_metadata(fs: Fs) -> DatasetMetadata:
    with fs.open(dataset_metadata_file_name, 'rt') as fp:
        return json.load(fp)


def load_dataset_from_metadata(fs: Fs, *args, **kwargs):
    # load metadata
    metadata = load_dataset_metadata(fs)
    loader_config = metadata["loader"]

    # resolve loader
    loader = importlib.import_module(loader_config["module"])
    for name in loader_config["qualname"].split("."):
        loader = getattr(loader, name)

    # exec loader
    loader_config_args = loader_config.get("args", None)
    loader_config_args = loader_config_args if loader_config_args is not None else ()
    args = (*loader_config_args, *args)

    loader_config_kwargs = loader_config.get("kwargs", None)
    loader_config_kwargs = loader_config_kwargs if loader_config_kwargs is not None else {}
    kwargs = {**loader_config_kwargs, **kwargs}

    # noinspection PyCallingNonCallable
    return loader(fs, *args, **kwargs)
